var pattern = new RegExp(/\?Code=(\S*)/g);
var idx = pattern.exec(window.location.href);
var Data02 = [];

var grid01 = $('#jgTable01'),
    grid02 = $('#jgTable02'),
    grid0m = $('#jgTable0m');

var postData02 = {
    Content:{
        Code: '',
        SearchText: ''
    }
},
postData0m = {
    Method: 'Q',
    Content:{
        SearchText: ''
    }
};
for(i in postData){
    postData02[i] = postData[i];
    postData0m[i] = postData[i];
};

$(function(){   
    requestAjax01();
    gridInit02();
    gridInit0m();
    $('li[data-opt="add"]').on('click', addBrands);
    $("li[data-opt='opt_search']").find(">i").on('click', function(){
        gridSearch.Content = {
            SearchText: $("#opt_search").find(">input").val()
        };
        search();
    });
    $('#addBtn').on('click', addSubmit);
    $('li[data-opt="u_save"],button[data-opt="u_save"]').on('click', saveSubmit);
    if(!idx){
        setTimeout("clickTr()",100);
    }else{
        setTimeout(function(){
            $('td[title="'+idx[1]+'"]').parent().trigger('click');
        },100);  
    }
    $('.modal-data').draggable({cancel:'.u_modal_body, input'}); 
});

function requestAjax01(){   //MDM0003/MDM000304
    var postData01 = {
        Method: 'Q',
        Content: {
            PCode: 0,
            Level: 1
        }
    };
    for(i in postData){
        postData01[i] = postData[i];
    }
    $.ajax({
        type: "post",
        url: mdmPath + "/MDM0003/MDM000304",
        data: postData01,
        dataType: "json",
        success: function(re) {
            loadAjax01(re);
        }
    });
}
function loadAjax01(re){    //checked
    if(re.Status == 200){
        if(re.Content){
            var Data01 = re.Content.rows;
            gridInit01(Data01)
        }
    } else if(re.Status == -999){
        alert_QX($('body'),re.Message);
    }else{
        myAlert(re.Message);
    }
}
function gridInit01(Data01){    //checked
    var gridData01 = Object.create(gridData);
    gridData01.grid = $('#jgTable01');
    gridData01.pager = $('#jgPager01');  
    gridData01.scroll = true;
    gridData01.height = '390px';
    gridData01.rownumbers = false;
    gridData01.datatype = "local";
    gridData01.colModel = [
        {label:'代码', name:'Code', hidden:true, sortable: false},
        {label:'<i class="fa fa-sort-amount-desc"></i>&nbsp;&nbsp;一级类别', name:'Name', sortable: false}
    ];
    gridData01.sortname = 'OrderID';
    gridData01.rowNum = 20;
    gridData01.beforeRequest = function(){
        gridData01.grid.jqGrid("setGridParam", {
            data : Data01
        });
    };
    gridData01.loadComplete = function(xhr){ 
        //clickTr();
    };
    gridData01.onSelectRow = function(rowid,status){
        var rowData = grid01.jqGrid('getRowData', rowid);
        // postData02 = {
        //     Content:{
        //         Code: rowData.Code,
        //         SearchText: ''
        //     }
        // };
        requestAjax02(rowData.Code);
        grid02.jqGrid('clearGridData').trigger('reloadGrid');
        history.pushState(null,'','MDM000302.html?Code='+rowData.Code);
        //clickTr();
    };
    gridInit(gridData01);
}

function requestAjax02(Code){
    var postData02 = Object.create(postData);
    postData02.Method = 'Q';
    postData02.page = 1;
    postData02.rows = 500;
    postData02.sidx = 'BrandCode';
    postData02.sord = 'Asc';
    postData02.Content = {
        Code: Code
    };
    $.ajax({
        async: false,
        type: "post",
        url: mdmPath + '/MDM0003/MDM000305',
        data: postData02,
        dataType: "json",
        success: function (re) {
            if (re.Status == 200) {
                loadAjax02(re);
            } else if (re.Status == -999) {
                alert_QX($('body'),re.Message);
            } else {
                alert(re.Message);
            }
        }
    });
}
function loadAjax02(re){
    if(re.Status == 200){
        if(re.Content){
            Data02 = re.Content.rows;
        }else{
            Data02 = [];
        }
        grid02.trigger("reloadGrid");
    }else{
        myAlert(re.Message);
    }
}
function alarmFormatter(cellvalue, options, rowdata){
    var grid = $(this);
    if(JSON.stringify(rowdata)!=='{}'){
        cellvalue = '<a href="javascript:0" opt-data="'+grid[0].id+'_delete" title="删除"><i class="fa fa-trash-o"></i></a>';
    }else{
        cellvalue = '';
    }
    return cellvalue;
}
function gridInit02(){
    var gridData02 = Object.create(gridData);
    gridData02.rowNum = '100';
    gridData02.grid = $('#jgTable02');
    //gridData02.pager = $('#jgPager02');    
    gridData02.datatype = "local";
    gridData02.colModel = [
        {label:'代码', name:'Code', hidden:true, sortable:false},
        {label:'行号', name:'LineID', hidden:true, sortable:false},
        {label:'代码', name:'BrandCode', sortable:false},
        {label:'名称', name:'BrandName', sortable:false},
        {label:'操作', name:'Options', width:80, formatter: alarmFormatter, sortable:false}
    ];
    gridData02.sortname = 'LineID';
    gridData02.loadComplete = function(xhr){
        $('a[opt-data="jgTable02_delete"]').unbind('click').bind('click', function(){
            var rowId = $(this).parent().parent()[0].id;
            grid02.jqGrid("delRowData", rowId);
            Data02 = grid02.jqGrid("getRowData");
        });
        gridData02.grid.jqGrid('sortableRows',{
            update:function(ev,ui){
                var item = ui.item[0],
                ri = item.rowIndex,
                itemId = item.id;
            }
        });
    };
    gridData02.beforeRequest = function(){
        gridData02.grid.jqGrid("setGridParam", {
            data : Data02
        });
    };
    gridInit(gridData02);
}

function gridInit0m(){
    var gridData0m = Object.create(gridData);
    gridData0m.grid = $('#jgTable0m');
    gridData0m.pager = $('#jgPager0m');
    gridData0m.height = '390px';   
    gridData0m.url = mdmPath + '/MDM0006/MDM000605';
    gridData0m.rowNum = 10;
    gridData0m.colModel = [
        {label:'代码', name:'Code'},
        {label:'名称', name:'Name'},
    ];
    gridData0m.sortname = 'Name';
    gridData0m.beforeRequest = function(){
        gridData0m.grid.jqGrid("setGridParam", {
            postData : postData0m
        });
    };
    gridData0m.loadComplete = function(xhr){
        //Search();
    }
    gridData0m.multiselect = true;
    gridInit(gridData0m);
    gridSearch = postData0m;
}

function addSubmit(){
    var rowData02 = grid02.jqGrid('getRowData');
    //console.log(rowData02)
    var rowIds = grid0m.jqGrid('getGridParam', 'selarrrow');
    var arr = [];
    rowIds.forEach(function(v,i,a){
        var temp = grid0m.jqGrid('getRowData', v);
        var status = true;
        rowData02.forEach(function(v,i,a){
            v.BrandCode == temp.Code&&(status = false);
        });
        status == true&&arr.push({Code:RegExp(/\?Code=(\S*)/g).exec(window.location.href)[1], BrandCode:temp.Code, BrandName:temp.Name});
    });
    Data02 = Data02.concat(arr);
    grid02.trigger("reloadGrid");
    if(arr.length>0){
        $('.modal-overlay').addClass('hidden');
    }else{
        myAlert('请选择您要添加的有效数据');
    }
}

function addBrands(){
    $('.modal-overlay').removeClass('hidden');
    gridSize();
}

function saveSubmit(){
    var MDM000302 = [];
    grid02.jqGrid("getRowData").forEach(function(v,i,a){
        MDM000302.push({Code:v.Code,LineID:i,BrandCode:v.BrandCode,BrandName:v.BrandName,OrderID:i});
    });
    var requestData = {
        Method: 'U',
        Content:{
            Code: RegExp(/\?Code=(\S*)/g).exec(window.location.href)[1],
            MDM000302: MDM000302
        }
    }
    for(i in postData){
        requestData[i] = postData[i];
    }
    console.log(requestData)
    $.ajax({
        type: 'post',
        url: mdmPath + '/MDM0003/MDM000306',
        data: requestData,
        dataType: "json",
        success: function (re) {
            if (re.Status == 200) {
                //grid02.trigger("reloadGrid");
                $('.modal-overlay').addClass('hidden');
                myAlert('保存成功');
            } else {
                myAlert(re.Message);
            }
        }
    });
}

function search(){
    //console.log(gridSearch)
    grid0m.jqGrid("setGridParam",{postData: gridSearch}).trigger("reloadGrid");
}

function gridSize(){
    grid02.setGridWidth($('.u_row .u_table_container').width());
    grid0m.setGridWidth($('.u_modal_body').width());
}

function clickTr(){
    grid01.find('>tbody>tr:nth-child(2)').trigger('click');
}

